import ajax from "./index"
export function downloadFile(url) {
  return new Promise(async (resolve, reject) => {
    wx.downloadFile({
      url: url,
      success: (res) => resolve(res.tempFilePath),
      fail: () => reject()
    })
  })
}

export const getImageInfo = (netUrl) => {
  return new Promise((resolve, reject) => {
    wx.getImageInfo({
      src: netUrl,
      success: (res) => res.errMsg == "getImageInfo:ok" ? resolve(res) : reject(res),
      fail: (err) => reject(err)
    })
  })
}

export function drawImage(ctx, bg_w, bg_h, imgPath, imgWidth, imgHeight, x, y) {
  let dWidth = bg_w / imgWidth;  // canvas与图片的宽度比例
  let dHeight = bg_h / imgHeight;  // canvas与图片的高度比例
  if (imgWidth > bg_w && imgHeight > bg_h || imgWidth < bg_w && imgHeight < bg_h) {
    if (dWidth > dHeight) {
      ctx.drawImage(imgPath, 0, (imgHeight - bg_h / dWidth) / 2 - 55, imgWidth, bg_h / dWidth, x, y, bg_w, bg_h)
    } else {
      ctx.drawImage(imgPath, (imgWidth - bg_w / dHeight) / 2, 0, bg_w / dHeight, imgHeight, x, y, bg_w, bg_h)
    }
  } else {
    if (imgWidth < bg_w) {
      ctx.drawImage(imgPath, 0, (imgHeight - bg_h / dWidth) / 2, imgWidth, bg_h / dWidth, x, y, bg_w, bg_h)
    } else {
      ctx.drawImage(imgPath, (imgWidth - bg_w / dHeight) / 2, 0, bg_w / dHeight, imgHeight, x, y, bg_w, bg_h)
    }
  }
}

export const canvasToTempFilePath = (canvasInfo) => {
  return new Promise((resolve, reject) => {
    wx.canvasToTempFilePath({
      canvasId: canvasInfo.id,
      x: 0,
      y: 0,
      width: canvasInfo.width,
      height: canvasInfo.height,
      fileType: "jpg",
      quality: 1,
      success: (res) => resolve(res.tempFilePath),
      fail: (err) => reject(err)
    })
  })
}



export function pageListFormat(arr = [], pageSize = 1) {
  let newArr = [], tmpArr = [];
  arr.forEach((item, index) => (tmpArr.push(item), (index % pageSize === pageSize - 1 || index === arr.length - 1 ? (newArr.push(tmpArr), tmpArr = []) : null)));
  return newArr;
}



export function getCanvas(canvasId) {
  return new Promise(async (resolve, reject) => {
    let query = wx.createSelectorQuery();
    query.select(canvasId).boundingClientRect(async (canvasInfo) => {
      const context = wx.createCanvasContext(canvasInfo.id);
      resolve({ context, canvasInfo })
    }).exec();
  })
}

export function setTextSplit(context, text, number, y, max) {
  if (!context || !text) return null
  console.log('setTextSplit', text)
  const strArr = pageListFormat(text.split(''), number)
  let textHeight = 20, count = 0
  context.fillStyle = "#333333"
  context.font = 'normal 500 14px sans-serif'
  strArr.forEach((item, index) => {
    if (index >= max) return
    count += 1
    let textStr = item.join('')
    if (max - 1 == index && textStr.length >= number) {
      textStr = textStr.substring(0, textStr.length - 3) + '...'
    }
    context.fillText(textStr, 10, (textHeight * index) + y)
  })
  context.setTextAlign('left')
  return count * textHeight + y
}

export function createParkPoster(canvasId, entity, type) {
  // return console.log('type--------------------', type, entity)
  return new Promise(async (resolve, reject) => {
    const { context, canvasInfo } = await getCanvas(canvasId)
    const userInfo = wx.getStorageSync('userInfo')
    const { width, height } = canvasInfo
    const cover = await downloadFile(entity.indexImage)
    const coverInfo = await getImageInfo(cover)
    const pageUrl = type == 'park' ? 'pagesEnterprise/pages/parkDetails/parkDetails' : type == 'enterprise' ? 'pagesEnterprise/pages/companyDetail/companyDetail' : 'pages/index/index'
    const codePath = await ajax.getQrCode({ id: entity.id, shareId: userInfo.id, page: pageUrl });
    const codeInfo = await getImageInfo(codePath)
    const headimgUrl = await downloadFile(userInfo.headimgUrl)
    context.fillStyle = "#FFFFFF";
    context.fillRect(0, 0, width, height)
    drawImage(context, width, 200, cover, coverInfo.width, coverInfo.height, 0, 0)
    drawImage(context, 100, 100, codePath, codeInfo.width, codeInfo.height, width - 110, height - 120)
    const titleHeight = 240
    const title = type == 'park' ? entity.gardenName : type == 'enterprise' ? entity.name : ''
    context.fillStyle = "#026064";
    context.font = `normal bold ${type == 'park' ? '30px' : '20px'} sans-serif`
    context.fillText(title || '暂无', 10, titleHeight)
    context.setTextAlign('left')
    const num = parseInt((width - 20) / 14)
    const textStr = type == 'park' ? entity.text : type == 'enterprise' ? entity.manageScope : ''
    setTextSplit(context, textStr, num, titleHeight + 30, 7)

    context.font = 'normal bold 14px sans-serif'
    context.fillText(userInfo.nickName + '邀您查看', 70, height - 85)
    context.font = 'normal bold 12px sans-serif'
    context.fillText('扫码立即加入 ▶', 70, height - 60)

    context.save();
    context.beginPath() // 开始创建一个路径
    context.strokeStyle = '#FFFFFF';
    context.arc(35, height - 80, 25, 0, Math.PI * 2, false)// 画一个圆形裁剪区域
    context.clip()// 裁剪
    context.drawImage(headimgUrl, 13, height - 105, 50, 50)

    context.stroke();
    context.save();
    context.draw();

    setTimeout(async () => {
      const filePath = await canvasToTempFilePath(canvasInfo)
      resolve(filePath)
    }, 300)
  })
}

export function createHousingPoster(canvasId, entity) {
  return new Promise(async (resolve, reject) => {
    console.log('createHousingPoster', entity)
    const { context, canvasInfo } = await getCanvas(canvasId)
    const userInfo = wx.getStorageSync('userInfo')
    const { width, height } = canvasInfo
    const indexImage = entity?.houseRent?.indexImage || ''
    if (!indexImage) return reject()
    const cover = await downloadFile(indexImage)
    const coverInfo = await getImageInfo(cover)
    const codePath = await ajax.getQrCode({ id: entity.houseRent.id, shareId: userInfo.id, page: 'pagesEnterprise/pages/houseDetail/houseDetail' });
    const codeInfo = await getImageInfo(codePath)
    const headimgUrl = await downloadFile(userInfo.headimgUrl)
    context.fillStyle = "#FFFFFF";
    context.fillRect(0, 0, width, height)
    drawImage(context, width, 200, cover, coverInfo.width, coverInfo.height, 0, 0)
    drawImage(context, 100, 100, codePath, codeInfo.width, codeInfo.height, width - 110, height - 120)
    console.log('createHousingPoster----------------3')
    const titleHeight = 240
    context.fillStyle = "#026064";
    context.font = `normal bold 20px sans-serif`
    context.textAlign = 'left';
    const roomNumber = entity.housingAssess.roomNumber.split(',')
    context.fillText(`${entity.houseRent.housingName || ''}${roomNumber.join('-')}`, 10, titleHeight)
    context.save();
    context.font = 'normal bold 14px sans-serif'
    context.textAlign = 'left';
    context.fillText(userInfo.nickName + '邀您查看', 70, height - 85)
    context.font = 'normal bold 12px sans-serif'
    context.fillText('扫码立即加入 ▶', 70, height - 60)
    context.textAlign = 'left';
    context.save();
    context.beginPath()
    context.lineWidth = 1;
    context.strokeStyle = '#F2F2F2';
    const lineaeY = titleHeight + 100
    context.moveTo(10, lineaeY);
    context.lineTo(width - 10, lineaeY);
    const lineX = width / 3, lineStartY = titleHeight + 40, lineEndY = titleHeight + 160
    context.moveTo(lineX * 1, lineStartY);
    context.lineTo(lineX * 1, lineEndY);
    context.moveTo(lineX * 2, lineStartY);
    context.lineTo(lineX * 2, lineEndY);
    context.stroke();


    context.font = 'normal 400 14px sans-serif'
    context.textAlign = 'center';
    context.fillStyle = "#999999";
    context.fillText('面积', (lineX / 2), lineaeY - 35)
    context.fillStyle = "#333333";
    context.fillText(`${entity?.housingAssess?.houseArea || '未知'}㎡`, (lineX / 2), lineaeY - 15)
    context.fillStyle = "#999999";
    context.fillText('朝向', (lineX * 2) - (lineX / 2), lineaeY - 35)
    context.fillStyle = "#333333";
    context.fillText(`${entity?.housingAssess?.orientation || '未知'}`, (lineX * 2) - (lineX / 2), lineaeY - 15)
    context.fillStyle = "#999999";
    context.fillText('层高', (lineX * 3) - (lineX / 2), lineaeY - 35)
    context.fillStyle = "#333333";
    context.fillText(`${entity?.housingAssess?.storeyHeight || '未知'}米`, (lineX * 3) - (lineX / 2), lineaeY - 15)

    const fitmentArr = ['精装修', '简装', '毛坯'];
    const fitmentCase = fitmentArr[entity.houseRent.fitmentCase - 0] || '未知'
    context.fillStyle = "#999999";
    context.fillText('装修', (lineX / 2), lineaeY + 30)
    context.fillStyle = "#333333";
    context.fillText(`${fitmentCase}`, (lineX / 2), lineaeY + 50)
    context.fillStyle = "#999999";
    context.fillText('房源格局', (lineX * 2) - (lineX / 2), lineaeY + 30)
    context.fillStyle = "#333333";
    context.fillText(`${entity?.housingAssess?.pattern || '未知'}`, (lineX * 2) - (lineX / 2), lineaeY + 50)
    context.fillStyle = "#999999";
    context.fillText('付款方式', (lineX * 3) - (lineX / 2), lineaeY + 30)
    context.fillStyle = "#333333";
    context.fillText(`${entity?.housingAssess?.paymentMethod || '待定'}`, (lineX * 3) - (lineX / 2), lineaeY + 50)

    context.save();
    context.beginPath() // 开始创建一个路径
    context.strokeStyle = '#FFFFFF';
    context.arc(35, height - 80, 25, 0, Math.PI * 2, false)// 画一个圆形裁剪区域
    context.clip()// 裁剪
    context.drawImage(headimgUrl, 13, height - 105, 50, 50)

    context.stroke();
    context.save();
    context.draw();
    setTimeout(async () => {
      const filePath = await canvasToTempFilePath(canvasInfo)
      resolve(filePath)
    }, 300)
  })
}